<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input
        v-model="form.name"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input
        v-model="form.code"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width: 80%" placeholder="请选择">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input
        v-model="form.introduce"
        style="width: 80%"
        placeholder="1-300个字符"
        type="textarea"
        :rows="3"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">确定</el-button>
      <el-button @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {
  getSimple,
  addDepartments,
  getDepartment,
  updataDepartment
} from '@/api/departments'

export default {
  props: {
    pid: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
      // value就是当前用户输入的编码，它不能与现有的编码数据（originList）重复
      // 如果重复，就验证不通过
      let codeList = this.originList.map(item => item.code)

      if (this.isEdit) {
        // 把当前正在编辑的部门编号（this.id）排除在外
        codeList = this.originList.filter(item => item.id !== this.pid).map(item => item.code)
      }

      console.log('codeList', codeList)
      // 检查value 是否存在其中
      codeList.includes(value)
        ? callback(new Error('编码' + value + '已经存在'))
        : callback()
    }
    const validName = (rule, value, callback) => {
      // 思路：被占用的名字是这个部门的子部门
      let nameList = this.originList.filter(item => item.pid === this.pid).map(item => item.name)
      console.log('被占用的名字列表', nameList)

      // 如果是编辑，则被占用的名字 = 兄弟-自己
      if (this.isEdit) {
        // 1. 找到当前被编辑的元素
        const item = this.originList.find(item => item.id === this.pid)
        // 2. 取出pid(它的父级是谁)
        const pid = item.pid
        // 3. 过滤： 同一个父级，不包括自己； map： 只要需要名字
        nameList = this.originList.filter(item => item.pid === pid && item.id !== this.pid).map(item => item.name)
      }
      console.log('被占用的名字列表', nameList)

      if (nameList.includes(value)) {
        callback(new Error('名字' + value + '已经被占用了'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '部门介绍要求1-300个字符',
            trigger: 'blur'
          }
        ]
      },
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      list: []
    }
  },
  created() {
    this.loadDeptDialog()
    // 如果是编辑就拿到部门信息
    if (this.isEdit) {
      this.loadDepartments()
    }
  },
  methods: {
    // 发请求获取编辑详情
    async loadDepartments() {
      const res = await getDepartment(this.pid)
      console.log('现在是编辑部门当前信息', res)
      // 数据回填
      this.form = res.data
    },
    // 获取弹框员工信息
    async loadDeptDialog() {
      const res = await getSimple()
      console.log('弹框员工信息', res)
      this.list = res.data
    },
    async doAdd() {
      try {
        // 调用接口
        const res = await addDepartments({ ...this.form, pid: this.pid })
        console.log('调用接口', res)
        this.$message({ type: 'success', message: '添加成功' })
        // 通知父组件：关闭弹层，再次更新数据
        this.$emit('success')
      } catch (err) {
        console.log(err)
      }
    },
    async doEdit() {
      try {
        // 调用接口
        const res = await updataDepartment(this.form)
        console.log('调用接口', res)
        this.$message({ type: 'success', message: '修改成功' })
        // 通知父组件：关闭弹层，再次更新数据
        this.$emit('success')
      } catch (err) {
        console.log(err)
      }
    },
    onSubmit() {
      // 表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 用户点击了取消
    hCancel() {
      // 通知父组件去关闭弹层
      this.$emit('close')
    }
  }
}
</script>

